#-*- coding: utf-8 -*-
from project.application import upload_db as  db
from flask import Blueprint, request, jsonify, render_template
import sys, os, datetime
from project.models import UploadFile

uploadBp = Blueprint("upload", __name__, url_prefix="/sync")

@uploadBp.route("/upload", methods=["GET", "POST"])
def sync_upload():
    """上传接口， 上传方式等待客户端确认
    """
    if request.method == "GET":
        return render_template("upload.html")

    cid = request.args.get("cid")
    if cid is None:
        return jsonify({"status": "failed"})
    
    file_dir = os.path.join(".", "upload", cid)
    if not os.path.isdir(os.path.join(".", "upload", cid)):
        try:
            os.makedirs(os.path.join(".", "upload", cid))
        except:
            return jsonify({"status": "unknow error"})

    d = datetime.datetime.now() 
   
    file_name = d.strftime("%Y-%m-%d-%H:%M:%S_%s") 
    upload_file = request.files["file"]
    
    file_ext = os.path.splitext(upload_file.filename)[-1]

    upload_file.save(os.path.join(file_dir, file_name + file_ext))
    return jsonify({"status": "ok"})


@uploadBp.route("/upload/end", methods=["GET", "POST"])
def sync_uploadEnd():
    cid = request.args.get("cid", None)
    if cid is None:
        return jsonify({"status": "failed", "reason": "no cid"})
 
    file_name        = request.form.get("file.name")
    file_path        = request.form.get("file.path")
    file_size        = request.form.get("file.size")
    file_md5         = request.form.get("file.md5")
    file_contentType = request.form.get("file.content_type") 
    upload_file = UploadFile(
                                file_name = file_name,
                                file_path  = file_path,
                                file_size = file_size,
                                file_md5 = file_md5,
                                file_cid = cid
                            )
    db.session.add(upload_file)
    db.session.commit()

    return jsonify({"status": "ok"})

